package com.madixin.chat.controller;

import com.madixin.chat.constants.Constants;
import com.madixin.chat.dto.ChatMessageRequest;
import com.madixin.chat.dto.ChatMessageResponse;
import com.madixin.chat.exception.ChatBaseException;
import com.madixin.chat.exception.ErrorCode;
import com.madixin.chat.model.ChatSession;
import com.madixin.chat.security.LoginUserDetails;
import com.madixin.chat.service.impl.ChatService;
import com.madixin.chat.service.impl.ChatSessionService;
import com.madixin.chat.service.impl.ChatMessageService;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;


@RestController
@SecurityRequirement(name = "BearerAuth")
@RequestMapping(value = "/chat")
public class ChatController {
    @Autowired
    private ChatService chatService;

    @Autowired
    private ChatSessionService chatSessionService;

    @Autowired
    private ChatMessageService chatMessageService;

    @PostMapping(value = "/message", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ChatMessageResponse> sendMessage(
//            @RequestHeader("Authorization") String authorization,
            @RequestParam("sessionId") String sessionId, @RequestParam("content") String content, @RequestParam("type") String type, @RequestParam(value = "image", required = false) MultipartFile image, @RequestParam(value = "options", required = false) String options) throws ChatBaseException {
        if (StringUtils.isBlank(sessionId) || sessionId.length() != Constants.UUID_SIZE) {
            throw new ChatBaseException(ErrorCode.ILLEGAL_PARAM);
        }
        // 1.根据sessionId查询session
        ChatSession chatSession = chatSessionService.getSessionById(sessionId);

        // 2.如果没有session，则创建新的session
        if (chatSession == null) {
            chatSession = new ChatSession();
            if (content.length() > 10) {
                chatSession.setTitle(content.substring(0, 10));
            } else {
                chatSession.setTitle(content);
            }
            LoginUserDetails loginUser = (LoginUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            chatSession.setUserId(loginUser.getUser().getId());
            chatSession.setId(sessionId);
            chatSessionService.createSession(chatSession);
        }

        // 构建请求对象
        ChatMessageRequest request = new ChatMessageRequest();
        request.setSessionId(sessionId);
        request.setContent(content);
        request.setType(type);
        request.setImage(image);
        request.setOptions(options);

        // 调用服务处理并返回流式响应
        return chatService.processRealMessage(request);
    }
}
